package com.zhang.zhangapp.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jwenfeng.library.pulltorefresh.BaseRefreshListener;
import com.jwenfeng.library.pulltorefresh.PullToRefreshLayout;
import com.zhang.zhangapp.LoginActivity;
import com.zhang.zhangapp.R;
import com.zhang.zhangapp.application.MApplication;
import com.zhang.zhangapp.base.config.BaseConfig;
import com.zhang.zhangapp.base.http.MCallback;
import com.zhang.zhangapp.bean.AdvData;
import com.zhang.zhangapp.bean.ZFile;
import com.zhang.zhangapp.bean.location.City;
import com.zhang.zhangapp.bean.location.CityDao;
import com.zhang.zhangapp.bean.shop.Shop;
import com.zhang.zhangapp.bean.shop.ShopType;
import com.zhang.zhangapp.http.CommonHttp;
import com.zhang.zhangapp.utils.T;
import com.zhang.zhangapp.view.adapter.BannerPagerAdapter;
import com.zhang.zhangapp.view.adapter.ShopAdapter;
import com.zhang.zhangapp.view.custom.HeadRefreshView;
import com.zhang.zhangapp.view.custom.IndicatorView;
import com.zhang.zhangapp.view.custom.ListViewInScrollView;
import com.zhang.zhangapp.view.mine.MessageListActivity;
import com.zhang.zhangapp.view.shop.AllShopTypeActivity;
import com.zhang.zhangapp.view.shop.ShopDetailActivity;
import com.zhang.zhangapp.view.shop.ShopListActivity;

import org.xutils.common.Callback;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2018/3/26.
 */
@ContentView(R.layout.fragment_home_index)
public class IndexFragment extends BaseLazyFragment {

    private int loadingCount = 0;

    private final static int SELECT_CITY = 10002;

    @ViewInject(R.id.index_refresh_layout)
    PullToRefreshLayout refreshLayout;

    @ViewInject(R.id.index_scrollview)
    ScrollView scrollView;

    @ViewInject(R.id.home_city_text)
    TextView cityText;


    private List<AdvData> advDataList = new ArrayList<>();

    /**
     * hot top
     */
    @ViewInject(R.id.home_hot_listview)
    ListViewInScrollView hotListView;

    ShopAdapter shopAdapter;

    private List<Shop> shopList = new ArrayList<>();

    @ViewInject(R.id.home_city_layout)
    LinearLayout cityLayout;

    @ViewInject(R.id.home_ad_image)
    ImageView homeAdImage;

    private ArrayList<ShopType> shopTypes = new ArrayList<>();

    /**
     * 轮播图
     */
    @ViewInject(R.id.index_ad_viewpager)
    private ViewPager mViewPager;
    /**
     * 指示器
     */
    @ViewInject(R.id.index_indicator)
    private IndicatorView mIndicatorView;
    /**
     * 适配器
     */
    private BannerPagerAdapter mBannerPagerAdapter;
    /**
     * 图片资源
     */
    private List<ZFile> pictureList = new ArrayList<>();
    /**
     * 轮播图自动轮播消息
     */
    public static final int AUTOBANNER_CODE = 0X1001;
    /**
     * 当前轮播图位置
     */
    private int mBannerPosition;
    /**
     * 自动轮播计时器
     */
    private Timer timer = new Timer();
    /**
     * 自动轮播任务
     */
    private BannerTimerTask mBannerTimerTask;
    /**
     * 用户当前是否点击轮播图
     */
    private boolean mIsUserTouched = false;
    /**
     * 轮播图Handler
     */

    private ArrayList<City> cityList;
    private double lon;
    private double lat;
    private String cityCode;//默认长沙
    Handler bannerHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            // 当用户点击时,不进行轮播
            if (!mIsUserTouched) {
                // 获取当前的位置
                mBannerPosition = mViewPager.getCurrentItem();
                // 更换轮播图
                mBannerPosition = (mBannerPosition + 1) % mBannerPagerAdapter.FAKE_BANNER_SIZE;
                mViewPager.setCurrentItem(mBannerPosition);
            }
            return true;
        }
    });

    Handler scrollViewHandler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_UP);
        }
    };

    /**
     * 获取推荐列表
     */
    MCallback getHotShopCallback = new MCallback() {
        @Override
        public void onSuccess(String data) {
            Gson gson = new Gson();
            List<Shop> list = gson.fromJson(data, new TypeToken<List<Shop>>() {
            }.getType());
            if (list != null) {
                shopList.addAll(list);
            }
            shopAdapter.notifyDataSetChanged();
            if (list.size() < BaseConfig.PAGE_SIZE) {
                refreshLayout.setCanLoadMore(false);
            }
        }

        @Override
        public void onSuccess(String message, String code) {
            T.showShort(getContext(), message);
            refreshLayout.setCanLoadMore(false);
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            T.showShort(getContext(), ex.getMessage());
            refreshLayout.setCanLoadMore(false);
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
            T.showShort(getContext(), cex.getMessage());
            refreshLayout.setCanLoadMore(false);
        }

        @Override
        public void onFinished() {
            loadingCount--;
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            if (loadingCount == 0) {
                dismisionDalog();
                scrollViewHandler.postDelayed(runnable, 200);
            }
        }
    };


    /**
     * 获取广告数据
     */
    MCallback getADData = new MCallback() {
        @Override
        public void onSuccess(String data) {
            Gson gson = new Gson();
            List<AdvData> list = gson.fromJson(data, new TypeToken<List<AdvData>>() {
            }.getType());
            if (list != null) {
                advDataList.addAll(list);
                for (AdvData advData : advDataList) {
                    if (advData.getSite().equals("0")) {
                        pictureList.addAll(advData.getAttachment());
                        initViewPager();
                    }
                    if (advData.getSite().equals("1") && advData.getAttachment() != null && advData.getAttachment().size() > 0) {
                        x.image().bind(homeAdImage, advData.getAttachment().get(0).getPicurl());
                    }
                }
            }
        }

        @Override
        public void onSuccess(String message, String code) {
            T.showShort(getContext(), message);
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            T.showShort(getContext(), ex.getMessage());
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
            T.showShort(getContext(), cex.getMessage());
        }

        @Override
        public void onFinished() {
            loadingCount--;
            if (loadingCount == 0) {
                dismisionDalog();
                scrollViewHandler.postDelayed(runnable, 200);
            }
        }
    };

    /**
     * 获取店铺类别数据
     */
    MCallback getShopTypeCallback = new MCallback() {
        @Override
        public void onSuccess(String data) {
            try {
                Gson gson = new Gson();
                List<ShopType> shopTypeList = gson.fromJson(data, new TypeToken<List<ShopType>>() {
                }.getType());
                if (shopTypeList != null) {

                    Iterator iterator = shopTypeList.iterator();
                    while (iterator.hasNext()) {
                        ShopType shopType = (ShopType) iterator.next();
                        if (shopType.getPid() == 0) {
                            shopTypes.add(shopType);
                            shopType.setChild(getChildShopType(shopType.getNo(), shopTypeList));
                        }
                    }
                    shopTypes.toArray();
                    MApplication.getInstance().setShopTypeArrayList(shopTypes);
                }
            } catch (Exception e) {
                Log.e("error", e.getMessage());
            }
        }

        @Override
        public void onSuccess(String message, String code) {

        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {

        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {
            loadingCount--;
            if (loadingCount == 0) {
                dismisionDalog();
                scrollViewHandler.postDelayed(runnable, 200);
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return x.view().inject(this, inflater, container);
    }

    @Override
    public void onFirstUserVisible() {
        initCityText();
        initHotListView();
        initRefreshLayout();
        getAdvData();
        getShopTypeData();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 递归生成类别
     *
     * @param no
     * @param typeList
     * @return
     */
    private List<ShopType> getChildShopType(String no, List<ShopType> typeList) {
        List<ShopType> list = new ArrayList<>();

        Iterator iterator = typeList.iterator();
        while (iterator.hasNext()) {
            ShopType shopType = (ShopType) iterator.next();
            // 数据结构有问题，只有两层
            if (no.substring(0, 2).equals(shopType.getNo().substring(0, 2)) && (Integer.valueOf(no)) % 100 == 0 && shopType.getPid() != 0) {
                list.add(shopType);
                List<ShopType> child = getChildShopType(shopType.getNo(), typeList);
                if (child != null && child.size() > 0) {
                    shopType.setChild(child);
                }
            }
        }
        return list;
    }

    private void initCityText() {
        if (MApplication.getInstance().getMapLocation() != null) {
            cityCode = CityDao.queryCityCode(MApplication.getInstance().getMapLocation().getCity().replace("市", ""));
            if (cityCode == null) {
                initCityInfoDefault();
            } else {
                lon = MApplication.getInstance().getMapLocation().getLongitude();
                lat = MApplication.getInstance().getMapLocation().getLatitude();
                cityText.setText(MApplication.getInstance().getMapLocation().getCity().replace("市", ""));
            }
        } else {
            initCityInfoDefault();
        }
    }

    private void initCityInfoDefault() {
        cityCode = BaseConfig.default_city_code;
        cityText.setText(BaseConfig.default_city_name);
        lat = BaseConfig.default_lat;
        lon = BaseConfig.default_lat;
    }

    private void updateCityByName(String cityName) {
        City city = CityDao.queryCityByName(cityName);
        if (city != null) {
            cityCode = city.getCode();
            lat = city.getDoubleClat();
            lon = city.getDoubleClon();
            this.cityText.setText(cityName);
            getHotShops(1);
        }
    }


    /**
     * init ad viewpager
     */
    private void initViewPager() {
        mBannerPagerAdapter = new BannerPagerAdapter(getContext(), pictureList);
        mViewPager.setAdapter(mBannerPagerAdapter);
        mIndicatorView.setViewPager(pictureList.size(), mViewPager);
        mViewPager.setCurrentItem(pictureList.size() * 100);
        startBannerTimer();
    }

    /**
     * 初始化headerView
     */
    private void initRefreshLayout() {
        refreshLayout.setHeaderView(new HeadRefreshView(getContext()));
        refreshLayout.setRefreshListener(new BaseRefreshListener() {
            @Override
            public void refresh() {
                shopList.clear();
                shopAdapter.notifyDataSetChanged();
                refreshLayout.setCanLoadMore(true);
                getHotShops(1);
            }

            @Override
            public void loadMore() {
                getHotShops(shopList.size() / BaseConfig.PAGE_SIZE + 1);
            }
        });
    }

    /**
     * 热门推荐
     */
    private void initHotListView() {
        shopAdapter = new ShopAdapter(shopList, getContext());
        hotListView.setAdapter(shopAdapter);
        hotListView.setFocusable(false);
        getHotShops(1);
        hotListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(IndexFragment.this.getActivity(), ShopDetailActivity.class);
                intent.putExtra("shopCode", shopList.get(position).getShopCode());
                IndexFragment.this.getActivity().startActivity(intent);

            }
        });
    }

    /**
     * 获取广告数据
     */
    private void getAdvData() {
        if (showLoadingDialog()) {
            loadingCount++;
            CommonHttp.commonHttp("hzg/mainData/advData", null, getADData);
        }
    }

    /**
     * 获取店铺类别
     */
    private void getShopTypeData() {
        if (showLoadingDialog()) {
            loadingCount++;
            CommonHttp.commonHttp("hzg/mainData/stypeData", null, getShopTypeCallback);
        }
    }

    /**
     * 获取热门推荐
     *
     * @param pageNo
     */
    private void getHotShops(int pageNo) {
        if (showLoadingDialog()) {
            if (pageNo == 1) {
                shopList.clear();
                shopAdapter.notifyDataSetChanged();
            }
            loadingCount++;
            Map<String, String> params = new HashMap<String, String>();
            params.put("lat", lat + "");
            params.put("lon", lon + "");
            params.put("cityCode", cityCode);
            params.put("orderkey", "1");
            params.put("pageNum", pageNo + "");
            params.put("pageSize", BaseConfig.PAGE_SIZE + "");
            CommonHttp.commonHttp("hzg/shop/queryShop", params, getHotShopCallback);
        }
    }

    /**
     * 开始轮播广
     */
    private void startBannerTimer() {
        if (timer == null) {
            timer = new Timer();
        }
        if (mBannerTimerTask != null) {
            mBannerTimerTask.cancel();
        }
        mBannerTimerTask = new BannerTimerTask(bannerHandler);
        if (timer != null && mBannerTimerTask != null) {
            // 循环5秒执行
            timer.schedule(mBannerTimerTask, 5000, 5000);
        }
    }

    @Event(type = View.OnClickListener.class, value = R.id.home_city_layout)
    private void cityLayoutClick(View view) {
        cityList = CityDao.queryAllCity();
        Intent intent = new Intent(getActivity(), CityPickerActivity.class);
        intent.putParcelableArrayListExtra("citys", cityList);
        startActivityForResult(intent, SELECT_CITY);
        getActivity().overridePendingTransition(R.anim.in_to_bottom, R.anim.out_to_up);
    }

    @Event(type = View.OnClickListener.class, value = R.id.action_bar_right_image)
    private void messageLayoutClick(View view) {
        if (MApplication.getInstance().getUser() != null) {
            Intent intent = new Intent(getActivity(), MessageListActivity.class);
            startActivity(intent);
        } else {
            goLoginActivity();
        }
    }

    /**
     * @param view
     */
    @Event(type = View.OnClickListener.class, value = {R.id.action_bar_title, R.id.home_food_layout, R.id.home_liren_layout, R.id.home_play_layout, R.id.home_more_layout, R.id.home_carservice_layout})
    private void shopTypeCilck(View view) {
        switch (view.getId()) {
            case R.id.action_bar_title: {//搜索
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                intent.putExtra("goShopList", true);
                startActivity(intent);
            }
            break;
            case R.id.home_food_layout://001 =
                openShopList("001", "美食");
                break;
            case R.id.home_liren_layout://002
                openShopList("002", "丽人");
                break;
            case R.id.home_play_layout://003
                openShopList("003", "娱乐");
                break;
            case R.id.home_carservice_layout://004
                openShopList("004", "汽车服务");
                break;
            case R.id.home_more_layout: {
                Intent intent = new Intent(getActivity(), AllShopTypeActivity.class);
                intent.putExtra("shopTypes", shopTypes);
                startActivity(intent);
            }
            break;
        }
    }

    private void goLoginActivity() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    private void openShopList(String type, String name) {
        Intent intent = new Intent(getActivity(), ShopListActivity.class);
        intent.putExtra("typeCode", type);
        intent.putExtra("title", name);
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {
                case SELECT_CITY://:
                    String cityName = data.getStringExtra(CityPickerFragment.KEY_PICKED_CITY);
                    updateCityByName(cityName);
                    break;
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mBannerTimerTask) {
            mBannerTimerTask.cancel();
            mBannerTimerTask = null;
        }
    }

    class BannerTimerTask extends TimerTask {
        /**
         * handler
         */
        Handler handler;

        public BannerTimerTask(Handler handler) {
            super();
            this.handler = handler;
        }

        @Override
        public void run() {
            handler.sendEmptyMessage(AUTOBANNER_CODE);
        }
    }
}
